import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
//导入Vue
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI);
//导入Axios
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios);

Vue.config.productionTip = false;

//Api服务地址
let apiUrl = "http://localhost:8888/";
Vue.prototype.$baseUrl = apiUrl;
//http request 拦截器
axios.interceptors.request.use(config=>{
	let username = localStorage.getItem("username");
	config.headers['username'] = username;
	return config;
},err=>{
	return Promise.reject(err);
});

//http response 拦截器
axios.interceptors.response.use(response=>{
	console.log("response:",response);
	let username = localStorage.getItem("username");
	response.headers.username = username;
	return response;
},err=>{
	console.log(err.response.status);
	return Promise.reject(err.response.status);
});

//控制路由,加载用户菜单信息
router.beforeEach((to,from,next)=>{
	//判断是否登录
	let userInfo = store.state.userInfo;
	// console.log("userInfo:",userInfo)
	if(to.path!='/' && (!userInfo || !userInfo.username)){
		next({
			path: '/'
		});
		
	}
	// console.log(to,from,next);
	if(to.path=='/index'){
		axios.get(apiUrl+"menu/getMenuVoListByUsername",{params:{username:'admin'}}).then(res=>{
			let menuData = res.data.data;
			let childrenRouters = [];
			menuData.forEach(menu=>{
				//二级菜单的路由
				let subMenus = menu.subMenus;
				subMenus.forEach(menu=>{
					console.log(menu);
					let newRouter = {
						name: menu.name,
						path: menu.path,
						iconCls: menu.iconCls
					}
					newRouter.component = () => import( './views/'+menu.component+'.vue');
					//router.options.routes[0].children.push(newRouter);
					//router.addRoutes(router.options.routes)
					childrenRouters.push(newRouter);
				});
			});
			
			//根据路由对象设置参数  下标的位置一定要根据 router/index.js中的routes数组决定。
			router.options.routes[0].children = childrenRouters;
			//加入到路由对象中
			router.addRoutes(router.options.routes);
			console.log("Vue.routes",router.options.routes[0].children)
		})
	}
	next();
})

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app');
